#!/usr/bin/env bash
#
#            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
#                    Version 2, December 2004
#
# Copyright (C) 2015 grugly https://notabug.org/grugly/ant
#
# Everyone is permitted to copy and distribute verbatim or modified
# copies of this license document, and changing it is allowed as long
# as the name is changed.
#
#            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
#   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
#
#  0. You just DO WHAT THE FUCK YOU WANT TO.
#
#

scr_name='Ant - Bash IRC tool'
scr_ver='0.3'
scr_auth='grugly'

printf '%s v%s by %s\n' "$scr_name" "$scr_ver" "$scr_auth"

usage() {
	printf 'Usage: %s [-n nick] [-u user] [-r "Real Name"] [-h irc.host.ext] [-p port]\n' "$0"
}

init() {
	while [ "$#" -ne '0' ]
	do
		ARG="$1"
		shift
		case "$ARG" in
			-n)	irc_nick="$1"; shift ;;
			-u)	irc_user="$1"; shift ;;
			-r)	irc_real="$1"; shift ;;
			-h)	irc_host="$1"; shift ;;
			-p)	irc_port="$1"; shift ;;
			*)	usage; exit ;;
		esac
	done

	[ -z "$irc_nick" ] && irc_nick='ant'
	[ -z "$irc_user" ] && irc_user='ant'
	[ -z "$irc_real" ] && irc_real='Ant IRC script'
	[ -z "$irc_host" ] && irc_host='irc.aard.xyz'
	[ -z "$irc_port" ] && irc_port='6667'

	irc_home="$HOME/irc"
	irc_log="$irc_home/$irc_host/log"
	irc_ext="$irc_home/$irc_host/inp"
	rpid_file="$irc_home/$irc_host/rpid"

	[ -d "$irc_home" ] || mkdir "$irc_home"
	[ -d "$irc_home/$irc_host" ] || mkdir "$irc_home/$irc_host"

	connect && external
}

log() {
	local raw="$1" time="$( printf '%(%s)T' )"
	local cmd="${raw:0:4}"

	[ "$cmd" = 'PING' ] && return
	[ "$cmd" = 'PONG' ] && return

	printf '%s %s\n' "$time" "$raw" >> $irc_log

	[ "$cmd" = 'QUIT' ] && die
}

connect() {
	[ -e "$rpid_file" ] && rdie
	[ -e "$irc_ext" ] || mkfifo "$irc_ext"
	printf 'Connecting to: %s:%s\n' "$irc_host" "$irc_port"
	exec {host}<>/dev/tcp/$irc_host/$irc_port || exit
	send "USER $irc_user $irc_host $irc_host $irc_real"
	send "NICK $irc_nick"

	receive &
	printf "$!" > "$rpid_file"
}

send() {
	local raw="$*"
	printf '%s\n' "$raw" >& $host
	log "$raw"
}

receive() {
	while true; do
		local raw='' ping='' info='' data=''
		read -r raw <& $host

		[ "$raw" = '' ] && connect
		raw="${raw%$'\r'}"

		IFS=':' read -r ping info data <<< "$raw"
		[ "$ping" = 'PING ' ] && send "PONG $info" || log "$raw"

		#$irc_home/src/in.sh "$info" "$data"
	done
}

external() {
	exec {ext}<$irc_ext || exit 1
	while true; do
		local raw=''
		read -r raw <&$ext
		[ "$raw" ] && send "$raw" || sleep 1
	done
}

rdie() {
	local rpid="$( cat "$rpid_file" )"
	kill "$rpid"
	wait "$rpid" 2>/dev/null
	rm "$rpid_file"
}

die() {
	rdie
	exit
}

init "$@"
